//
//  AddNewArtist.m
//  XMLtoCD08
//
//  Created by Miles on 10-03-24.
//  Copyright 2010 Miles Thorogood
//  greenmeat.net. All rights reserved.
//

#import "AddNewArtist.h"
#import "Artist.h"

@implementation AddNewArtist

@synthesize artist ;

- (id) init {
	self = [super init] ;
	
	return self ;
}

- (void) populateArtist:(NSDictionary *) dataDictionary {
		if (dataDictionary != NULL) {
			
			NSString *lName = [dataDictionary objectForKey:@"last_name"] ;
			NSString *fName = [dataDictionary objectForKey:@"first_name"] ;
			NSString *stream = [dataDictionary objectForKey:@"program_type"] ;
			NSString *medium = [dataDictionary objectForKey:@"medium"] ;
			NSString *text = [dataDictionary objectForKey:@"text"] ;
			NSString *year = [dataDictionary objectForKey:@"timestamp"] ;
			NSString *imgURL = [dataDictionary objectForKey:@"filepath"] ;
			
			NSDate *date = [self stringToDate:year] ;

			artist.lastname = lName ;
			artist.firstname = fName ;
			artist.text = text ;
			artist.date = date ;
			artist.program = stream ;
			artist.filepath = imgURL ;
			artist.medium = medium ;
			
			ArtistImage *image = [NSEntityDescription insertNewObjectForEntityForName:@"ArtistImage" inManagedObjectContext:artist.managedObjectContext];
			artist.artistImage = image;
			NSString *imageURL = artist.filepath ;
			
			NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
			UIImage *artistlImage = [[UIImage alloc] initWithData:imageData];
			//UIImage *artistlImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"img1_360x240_72" ofType:@"jpg"]];
			
			[image setValue:artistlImage forKey:@"artistImage"];

			CGSize size = artistlImage.size;
			CGFloat ratio = 0;
			if (size.width > size.height) {
				ratio = 128.0 / size.width;
			} else {
				ratio = 130.0 / size.height;
			}
			CGRect rect = CGRectMake(0.0, 0.0, ratio * size.width, ratio * size.height);
			
			UIGraphicsBeginImageContext(rect.size);
			[artistlImage drawInRect:rect];
			artist.artistThumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
			
			// Save the context.
			NSError *error = nil;
			if (![artist.managedObjectContext save:&error]) {
				NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
				abort();
			}
		}
	
}

- (NSDate *) stringToDate:(NSString *) datestring {	
	// Convert string to date object
	NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	[dateFormat setDateFormat:@"yyyy-MM-dd"];
	NSDate *date = [dateFormat dateFromString:datestring];  
	
	// Convert date object to desired output format
	[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
	datestring = [dateFormat stringFromDate:date];  
	[dateFormat release];
	NSLog(@"date is %@", datestring) ;
	
	return date ;
}

@end
